package cn.edu.sdjzu.xg.kcsj.controller.authority;

import cn.edu.sdjzu.xg.kcsj.security.*;
import cn.edu.sdjzu.xg.kcsj.util.JSONUtil;
import cn.edu.sdjzu.xg.kcsj.util.JwtUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

@WebServlet("/login.ctl")
public class LoginController extends HttpServlet {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(LoginController.class);
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String actor_json = JSONUtil.getJSON(request);
        //将JSON字串解析为User对象
        User userToLogin =  JSON.parseObject(actor_json, User.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            User currentUser = UserService.getInstance().login(userToLogin.getUsername(),userToLogin.getPassword());
            if (currentUser == null) {
                message.put("message", "用户名或密码不匹配");
                log.debug("用户名或密码不匹配");
                response.getWriter().println(JSON.toJSONString(message));
            } else {
                log.debug("用户名或密码匹配");
                message.put("user", currentUser);
                String token = JwtUtil.createToken(currentUser, 1);
                //将token放入响应头
                response.setHeader("token",token);
                //输出JSON字串时，屏蔽某些字段
                //SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
                //FastJson生成JSON数据时，排除"department"字段
                //filter.getExcludes().add("no");
                //filter.getExcludes().add("department");
                //根据filter的设置,响应数据
                response.getWriter().println(JSON.toJSONString(message));
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //响应message到前端
            response.getWriter().println(message);
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            //响应message到前端
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }
}
